<template>
  <div class="user-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="handleEdit($event)"
        >
          添加
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.MatchString"
              clearable
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>
    <el-table
      ref="tableSortRef"
      v-loading="listLoading"
      :border="border"
      :data="list"
      :height="height"
      :size="lineHeight"
      :stripe="stripe"
      @selection-change="setSelectRows"
    >
      <el-table-column
        v-for="(item, index) in finallyColumns"
        :key="index"
        align="center"
        :label="item.label"
        :prop="item.prop"
        :sortable="item.sortable"
        width="auto"
      >
        <template slot-scope="scope">
          <template v-if="item.prop == 'ProductId'">
            <el-link :underline="false" type="success">
              {{ scope.row[item.prop] }}
            </el-link>
          </template>
          <template v-else-if="item.prop == 'PlanNum'">
            <el-link :underline="false" type="primary">
              {{ scope.row[item.prop] }}
            </el-link>
          </template>
          <template v-else-if="item.prop == 'CompleteRate'">
            <el-progress :percentage="scope.row[item.prop]"></el-progress>
          </template>
          <template v-else>
            <span>{{ scope.row[item.prop] }}</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        show-overflow-tooltip
        width="200"
      >
        <template slot-scope="scope">
          <!-- <el-button @click="handleEdit(scope.row)">编辑</el-button> -->
          <el-button
            text
            type="primary"
            @click.stop="handleCreate(scope.row)"
            v-if="!scope.row.IsCreated"
          >
            生成工单
          </el-button>
          <el-button type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
      <template slot="empty">
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <el-dialog
      :close-on-click-modal="false"
      :visible="dialogVisible"
      :title="title"
      width="80%"
      :before-close="handleClose"
    >
      <div>
        <div style="margin-bottom: 20px">
          <el-select
            v-model="value"
            class="m-2"
            placeholder="选择订单"
            size="large"
            @change="changeOrder"
          >
            <el-option
              v-for="item in produceOrderData"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <div style="margin-bottom: 30px" v-for="(item, index) in ProductInfo">
          <el-descriptions :title="'产品' + (index + 1)" :column="3" border>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                产品编号:
              </template>
              {{ item.ProductId }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                订单数量
              </template>
              <el-tag size="small">{{ item.Num }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                已计划生产数量
              </template>
              <el-tag size="small">{{ item.TotalPlanNum }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                完成数量:
              </template>
              <el-tag size="small">{{ item.TotalCompleteNum }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                完成率
              </template>
              <el-progress
                :text-inside="true"
                :stroke-width="26"
                :percentage="item.CompleteRate"
              />
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">操作</template>
              <el-button type="primary" @click="productIdAdd(item)">
                添加
              </el-button>
            </el-descriptions-item>
          </el-descriptions>
          <el-table
            ref="singleTableRef"
            :data="item.PlanInfo"
            highlight-current-row
            style="width: 100%; margin-top: 20px"
            @current-change="handleCurrentChange"
            size="mini"
          >
            <el-table-column label="计划编号" width="250">
              <template slot-scope="scope">
                <el-popover
                  placement="top-start"
                  title="计划编号"
                  width="300"
                  trigger="hover"
                  :content="scope.row.PlanId"
                >
                  <!-- <el-button slot="reference">hover 激活</el-button> -->
                  <div
                    style="
                      width: 250px;
                      text-overflow: ellipsis;
                      white-space: nowrap;
                      overflow: hidden;
                    "
                    slot="reference"
                  >
                    {{ scope.row.PlanId }}
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column property="PlanStartTime" label="计划开工日期" />
            <el-table-column
              property="PlanStartWeekDay"
              label="星期"
              width="100"
            />
            <el-table-column property="PlanEndTime" label="计划完工日期" />
            <el-table-column property="ProduceOrderId" label="订单编号" />
            <el-table-column property="ProductId" label="产品编号" />
            <el-table-column property="PlanNum" label="计划量" width="100" />
            <el-table-column
              property="CompleteNum"
              label="完成量"
              width="100"
            />
            <el-table-column
              property="CompleteRate"
              label="完成率"
              width="100"
            />
            <el-table-column property="PlanNum" label="是否生成">
              <template slot-scope="scope">
                {{ scope.row.IsCreated ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- <el-button size="small" type="primary" @click="handleCreate(row)">生成工单</el-button> -->
                <el-button
                  v-if="scope.row.CanDelete"
                  size="mini"
                  type="danger"
                  @click.stop="handleDelete(scope.row, 2)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template slot="footer">
        <span class="dialog-footer">
          <el-button
            type="primary"
            @click="
              dialogVisible = false
              fetchData()
            "
          >
            确定
          </el-button>
          <!-- <el-button type="primary" @click="submit">保存</el-button> -->
        </span>
      </template>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :visible="dialogVisible1"
      title="编辑"
      width="50%"
      :before-close="handleClose1"
    >
      <el-form :model="form" labelWidth="150px">
        <el-form-item label="计划生产时间">
          <!-- <el-date-picker
            @change="startTimes"
            v-model="form.StartTime"
            type="date"
            label="请选择计划开始生产时间"
            placeholder="请选择计划开始生产时间"
            style="width: 100%"
          /> -->
          <el-date-picker
            @change="startTimes"
            v-model="form.date"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始生产时间"
            end-placeholder="结束生产时间"
          ></el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="计划结束生产时间">
          <el-date-picker
            v-model="form.EndTime"
            type="date"
            label="请选择计划结束生产时间"
            placeholder="请选择计划结束生产时间"
            style="width: 100%"
          />
        </el-form-item> -->
        <el-form-item label="计划数量">
          <el-input v-model="form.PlanNum" :rows="2" type="text" />
        </el-form-item>
        <el-form-item label="计划开始星期">
          <el-input
            v-model="form.StartWeekDay"
            :rows="2"
            type="text"
            readonly
          />
        </el-form-item>
        <el-form-item label="检测方式">
          <el-select v-model="form.DetectAction" placeholder="请选择">
            <el-option
              v-for="item in DetectAction"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="间隔件数" v-if="form.DetectAction == '间隔检测'">
          <el-input v-model="form.InterVal" :rows="2" type="text" />
        </el-form-item>
      </el-form>
      <template slot="footer">
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import {
    planOrderList,
    ProducePlan,
    ProduceOrderIdList,
    AllProductPlanInfo,
    ProducePlanDel,
    ProducePlanOrderNewly,
    GenerateProduct,
    GetDetectAction,
  } from '@/api/production'

  export default {
    data() {
      return {
        value: '',
        TrayInfoData: [],
        form: {
          date: '',
          StartTime: '',
          EndTime: '',
          PlanNum: '',
          StartWeekDay: '',
          DetectAction: '',
        },
        radio: 3,
        formLabelWidth: '100px',
        dialogVisible: false,
        tableSortRef: null,
        editRef: null,
        border: true,
        height: this.$baseTableHeight(1),
        stripe: false,
        lineHeight: 'small',
        isFullscreen: false,
        checkList: [
          '计划工单编号',
          '计划开工时间',
          '计划开工星期',
          '计划完工时间',
          '生产订单编号',
          '产品编号',
          '计划数量',
          '完成数量',
          '完成率',
        ],
        columns: [
          {
            label: '计划工单编号',
            prop: 'PlanId',

            disableCheck: true,
          },
          {
            label: '计划开工时间',
            prop: 'PlanStartTime',

            disableCheck: true,
          },
          {
            label: '计划开工星期',
            prop: 'PlanStartWeekDay',
          },
          {
            label: '计划完工时间',
            prop: 'PlanEndTime',
          },
          {
            label: '生产订单编号',
            prop: 'ProduceOrderId',
          },
          {
            label: '产品编号',
            prop: 'ProductId',
          },
          {
            label: '计划数量',
            prop: 'PlanNum',
          },
          {
            label: '完成数量',
            prop: 'CompleteNum',
          },
          {
            label: '完成率',
            prop: 'CompleteRate',
          },
        ],
        list: [],
        imageList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          pageNo: 1,
          pageSize: 20,
          MatchString: '',
        },
        title: '添加',
        produceOrderData: [],

        dialogVisible1: false,

        ProduceOrderId: '',
        ProductInfo: {},
        ProductNum: 0,
        TotalPlanNum: 0,

        DetectAction: [],
      }
    },
    computed: {
      finallyColumns() {
        return this.columns.filter((item) =>
          this.checkList.includes(item.label)
        )
      },
    },
    created() {
      this.fetchData()
    },
    methods: {
      handleCreate(item) {
        GenerateProduct({ PlanId: item.PlanId }).then((res) => {
          this.$baseMessage('成功', 'success', 'vab-hey-message-error')
          this.fetchData()
        })
      },
      productIdAdd(item) {
        GetDetectAction().then((res) => {
          console.log('sss', res)
          this.DetectAction = res.DetectAction
        })
        this.dialogVisible1 = true
        this.ProductId = item.ProductId
        this.ProductNum = item.Num
        this.TotalPlanNum = item.TotalPlanNum
      },
      startTimes(e) {
        const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

        this.form.StartTime = this.days(e[0])
        this.form.EndTime = this.days(e[1])
        // return false
        const today = new Date(e[0])
        const weekday = today.getDay()
        this.form.StartWeekDay = days[weekday]
      },
      changeOrder(ProduceOrderId) {
        console.log('row', ProduceOrderId)
        this.ProduceOrderId = ProduceOrderId
        planOrderList({ ProduceOrderId }).then((res) => {
          this.ProductInfo = res.ProductInfo
        })
      },
      handleSelectionChange(e) {
        this.form.ApplyProduct = e.map((item) => {
          return item.ProducationName
        })
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      submit() {
        this.form.ProduceOrderId = this.ProduceOrderId
        this.form.ProductId = this.ProductId
        this.form.StartTime = this.days(this.form.StartTime)
        this.form.EndTime = this.days(this.form.EndTime)
        const num = this.ProductNum - this.TotalPlanNum
        if (num <= 0) {
          this.$baseMessage('计划数量超出', 'error', 'vab-hey-message-error')
          return false
        }
        if (parseFloat(this.form.PlanNum) > num) {
          this.$baseMessage('计划数量超出', 'error', 'vab-hey-message-error')
          return false
        }
        ProducePlanOrderNewly(this.form).then((res) => {
          this.$baseMessage('成功', 'success', 'vab-hey-message-success')
          this.dialogVisible1 = false
          this.changeOrder(this.ProduceOrderId)
        })
      },
      handleEdit(row) {
        this.produceOrder()
        // if (row.MaterialType) {
        //   this.title = '编辑'
        //   this.form = row
        // } else {
        //   this.title = '添加'
        // }

        this.dialogVisible = true
      },
      produceOrder() {
        ProduceOrderIdList().then((res) => {
          this.produceOrderData = res.ProducceOrderList
        })
      },
      handleDelete(row, index) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const { msg } = await ProducePlanDel({
            PlanId: row.PlanId,
          })
          // $baseMessage(msg, 'success', 'vab-hey-message-success')
          if (index == 2) {
            this.changeOrder(this.ProduceOrderId)
          } else {
            await this.fetchData()
          }
        })
        return false
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ ids: row.id })
            this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            await this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids })
              this.$baseMessage(msg, 'success', 'vab-hey-message-success')
              await this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      },
      handleClose() {
        this.dialogVisible = false
      },
      handleClose1() {
        this.dialogVisible1 = false
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const params = {
          Index: this.getPage(this.queryForm.pageNo, this.queryForm.pageSize),
          Count: this.queryForm.pageSize,
          MatchString: this.queryForm.MatchString,
        }
        AllProductPlanInfo(params).then((res) => {
          console.log('MaterInfo', res)
          this.list = res.PlanInfo
          this.total = res.TotalCount
          this.listLoading = false
        })
      },
    },
  }
</script>
